﻿using System.Web.Mvc;
using System.Web.Security;
using TP_02.Models;

namespace TP_02.Controllers {

    public class AuthController : Controller {
        [HttpGet]
        public ActionResult Create() {
            return View();
        }

        [HttpPost]
        public ActionResult Create(User user)
        {
            try
            {
                if (!user.Password.Equals(user.PasswordRepeated))
                {
                    ModelState.AddModelError("PasswordRepeated",
                    "Les deux mot de passe doivent être identique...");
                } 

                if (ModelState.IsValid)
                {
                    user.SaveAsNew();
                    return RedirectToAction("Index", "Home");
                }
                return View(user);
            }
            catch
            {
                return View();
            }
        }

        [HttpGet]
        public ActionResult Login(string returnUrl) {
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.error = "";
            return View();
        }

        [HttpPost]
        public ActionResult Login(string username, string password, string returnUrl = "")
        {
            ViewBag.error = "";
            ViewBag.ReturnUrl = returnUrl;
            if (!Models.User.IsValid(username, password))
            {
                ViewBag.error = "Le compte n'existe pas ou le mot de passe est invalide!";
                return View();
            }
            FormsAuthentication.SetAuthCookie(username, false);
            if (returnUrl == "")
            {
                return RedirectToAction("Index", "Home");
            }
            return Redirect(returnUrl);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}
